package foo.base;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;

import foo.websystem.action.Consts;
import foo.websystem.vo.SessionUser;

public class LoginFilter implements Filter {

	private FilterConfig filterConfig;

	private String[] ignoreUrls = new String[] { HOME_URL, "login.do","error" };
	private String initUrl;
	protected Logger logger = Logger.getLogger(getClass());

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		try {
			HttpSession session = req.getSession();
			boolean pass = false;
			String requestUrl = req.getRequestURI();
			logger.debug("Filter:" + requestUrl);
			// if (!session.isNew()) { //
			// 可能有container面錯誤；session不見得是新的，但user物件已不存在
			// pass = true;
			// }
			SessionUser user = (SessionUser) session.getAttribute(Consts.USER);
			if (user == null) {// 如果是不需要認證頁面
				for (String ignoreUrl : ignoreUrls) {
					if (requestUrl.contains(ignoreUrl)) {
						pass = true;
						break;
					}
				}
			} else {
				pass = true;
			}
			if (pass) {
				chain.doFilter(request, response);
			} else {
				req.getRequestDispatcher(HOME_URL).forward(request, response);
			}
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
			request.setAttribute(Consts.MSG, "系統錯誤:" + e.getMessage());
			req.getRequestDispatcher("/error.jsp").forward(request, response);
		}
	}

	/** initLogin.do */
	private static final String HOME_URL = "/initLogin.do";

	public void init(FilterConfig filterConfig) throws ServletException {
		initUrl = filterConfig.getServletContext().getContextPath() + HOME_URL;
	}

	public void destroy() {

	}

}
